package com.itheima.tlias.service.impl;

import com.itheima.tlias.annotation.Log;
import com.itheima.tlias.mapper.DeptMapper;
import com.itheima.tlias.mapper.EmpMapper;
import com.itheima.tlias.pojo.Dept;
import com.itheima.tlias.pojo.DeptLog;
import com.itheima.tlias.service.DeptLogService;
import com.itheima.tlias.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 部门业务实现
 * @author
 * @version 1.0.1
 * @date 2023-04-07 15:25:59
 */
@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private DeptLogService deptLogService;

    @Override
    public void add(Dept dept) {
        // 1.校验参数
        if(dept == null
            || dept.getName() == null
            || "".equals(dept.getName().trim())) {
            throw new RuntimeException("非法参数");
        }
        // 2.处理业务
        // 2.1 补全实体
        LocalDateTime now = LocalDateTime.now();
        dept.setCreateTime(now);
        dept.setUpdateTime(now);
        deptMapper.insert(dept);
        // 3.封装数据
    }

    //@Transactional ： spring事务管理
    @Transactional(rollbackFor = Exception.class)
    //rollbackFor = Exception.class（表示出现所有的异常都可以进行事务的回滚）
    @Override
    @Log
    //根据ID删除部门数据
    public void delete(Integer id) throws Exception {
        // 1.校验参数
        if (id == null) {
            //抛出一个异常
            throw new RuntimeException("非法参数");
        }
        // 2.处理业务
        //2.1 删除部门
        try {
            deptMapper.delete(id);
            /*if (true) {
                throw new Exception("出异常了");
            }*/
            //2.2 根据部门ID删除该部门下的员工员工
            empMapper.deleteByDeptId(id);
            // 3.封装数据
        }finally {
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("进行了删除" + id + "号部门的操作");
            deptLogService.insert(deptLog);
        }
    }
    @Log
    @Override
    public List<Dept> findAll() {
        //1.校验参数
        //2.处理业务
        List<Dept> depts = deptMapper.findAll();
        //3.封装数据
        return depts;
    }
}
